<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 对话助手</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    animation: {
                        'fade-in': 'fadeIn 0.3s ease-in-out',
                        'slide-up': 'slideUp 0.3s ease-out',
                        'typing': 'typing 1.5s ease-in-out infinite',
                    },
                    keyframes: {
                        fadeIn: {
                            '0%': { opacity: '0', transform: 'translateY(10px)' },
                            '100%': { opacity: '1', transform: 'translateY(0)' }
                        },
                        slideUp: {
                            '0%': { opacity: '0', transform: 'translateY(20px)' },
                            '100%': { opacity: '1', transform: 'translateY(0)' }
                        },
                        typing: {
                            '0%, 100%': { opacity: '1' },
                            '50%': { opacity: '0.3' }
                        }
                    }
                }
            }
        }
    </script>
    <style>
        .message-content {
            word-wrap: break-word;
            white-space: pre-wrap;
        }
        .typing-indicator {
            animation: typing 1.5s ease-in-out infinite;
        }
        .scroll-smooth {
            scroll-behavior: smooth;
        }
        .glass-effect {
            backdrop-filter: blur(10px);
            background: rgba(255, 255, 255, 0.8);
        }
        .gradient-border {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 1px;
            border-radius: 12px;
        }
        .gradient-border-inner {
            background: white;
            border-radius: 11px;
        }
        .custom-scrollbar::-webkit-scrollbar {
            width: 6px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 3px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 3px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }
    </style>
</head>
<body class="bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 min-h-screen">

<!-- 主容器 -->
<div class="max-w-5xl mx-auto h-screen flex flex-col">

    <!-- 顶部栏 -->
    <header class="glass-effect border-b border-white/20 p-6 shadow-sm">
        <div class="flex items-center justify-between">
            <div class="flex items-center space-x-3">
                <div class="w-10 h-10 bg-gradient-to-r from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
                    <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path>
                    </svg>
                </div>
                <div>
                    <h1 class="text-xl font-bold bg-gradient-to-r from-gray-800 to-gray-600 bg-clip-text text-transparent">AI 对话助手</h1>
                    <p class="text-sm text-gray-500">智能对话，即时响应</p>
                </div>
            </div>
            <div class="flex items-center space-x-4">
                <div class="gradient-border">
                    <div class="gradient-border-inner">
                        <select id="modelSelect" class="text-sm px-4 py-2 focus:outline-none bg-transparent">
                            <option value="deepseek-r1:1.5b">DeepSeek R1 1.5B</option>
                            <option value="llama2">Llama 2</option>
                            <option value="qwen">Qwen</option>
                        </select>
                    </div>
                </div>
                <div class="flex items-center space-x-2">
                    <div id="statusIndicator" class="w-3 h-3 rounded-full bg-gray-400 shadow-sm"></div>
                    <span id="statusText" class="text-xs text-gray-500">离线</span>
                </div>
                <button onclick="toggleUploadModal()"
                        class="text-sm bg-gradient-to-r from-purple-600 to-indigo-600 text-white px-4 py-2 rounded-lg shadow hover:shadow-md transition">
                    📚 上传知识库
                </button>
                <button id="showRagListBtn"
                        class="text-sm bg-gradient-to-r from-green-600 to-teal-600 text-white px-4 py-2 rounded-lg shadow hover:shadow-md transition">
                    📋 查看知识库列表
                </button>

            </div>
        </div>
    </header>
    <!-- 知识库列表弹窗 -->
    <div id="ragListModal" class="fixed inset-0 z-50 bg-black/40 hidden items-center justify-center flex">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6 relative animate-fade-in max-h-[80vh] overflow-auto">
            <button onclick="toggleRagListModal()"
                    class="absolute top-3 right-3 text-gray-400 hover:text-gray-600 text-xl font-bold">&times;</button>
            <h2 class="text-xl font-bold text-gray-800 mb-4">📚 知识库列表</h2>
            <ul id="ragListContainer" class="list-disc list-inside space-y-2 text-gray-700 max-h-[60vh] overflow-auto"></ul>
            <div id="ragListLoading" class="text-center text-gray-500 mt-4 hidden">加载中...</div>
            <div id="ragListError" class="text-red-500 mt-4 hidden"></div>
        </div>
    </div>


    <!-- 聊天消息区域 -->
    <div id="messagesContainer" class="flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar">
        <div class="text-center py-12">
            <div class="w-16 h-16 bg-gradient-to-r from-blue-500 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
                <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                </svg>
            </div>
            <h3 class="text-lg font-semibold text-gray-700 mb-2">开始与AI助手对话</h3>
            <p class="text-gray-500 text-sm">输入您的问题，我将为您提供智能回答</p>
        </div>
    </div>

    <div class="flex space-x-4 items-start mb-2">
        <!-- 模式选择 -->
        <div>
            <label class="text-sm text-gray-600 block mb-1">问答模式</label>
            <select id="qaModeSelect"
                    class="text-sm px-3 py-2 rounded-lg border border-gray-300 shadow-sm focus:ring-2 focus:ring-blue-400 bg-white">
                <option value="normal">普通模式</option>
                <option value="rag">知识库问答</option>
            </select>
        </div>

        <!-- 选择知识库，仅知识库模式下显示 -->
        <div id="ragTagSelectorContainer" class="hidden">
            <label class="text-sm text-gray-600 block mb-1">知识库选择</label>
            <select id="ragTagSelector"
                    class="text-sm px-3 py-2 rounded-lg border border-gray-300 shadow-sm focus:ring-2 focus:ring-blue-400 bg-white min-w-[160px]">
                <option value="">加载中...</option>
            </select>
        </div>
    </div>
    <!-- 输入区域 -->
    <div class="glass-effect border-t border-white/20 p-6">
        <div class="max-w-4xl mx-auto">
            <div class="flex space-x-4">
                <div class="flex-1 relative">
                    <textarea id="messageInput" placeholder="输入您的问题，按 Ctrl+Enter 快速发送..."
                              class="w-full resize-none border-2 border-gray-200 rounded-2xl px-6 py-4 focus:outline-none focus:border-blue-500 focus:ring-4 focus:ring-blue-500/10 transition-all duration-200 shadow-sm bg-white/80 backdrop-blur-sm"
                              rows="1" maxlength="1000"></textarea>
                    <div class="absolute bottom-3 right-4 text-xs text-gray-400">
                        <span id="charCount">0/1000</span>
                    </div>
                </div>
                <button id="sendButton"
                        class="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 disabled:from-gray-400 disabled:to-gray-400 disabled:cursor-not-allowed text-white px-8 py-4 rounded-2xl font-medium transition-all duration-200 flex items-center space-x-2 shadow-lg hover:shadow-xl transform hover:scale-105 disabled:transform-none">
                    <svg id="sendIcon" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>
                    </svg>
                    <span id="sendText">发送</span>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 上传知识库弹窗 -->
<div id="uploadModal" class="fixed inset-0 z-50 bg-black/40 hidden items-center justify-center flex">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6 relative animate-fade-in">
        <!-- 关闭按钮 -->
        <button onclick="toggleUploadModal()"
                class="absolute top-3 right-3 text-gray-400 hover:text-gray-600 text-xl font-bold">&times;</button>

        <h2 class="text-xl font-bold text-gray-800 mb-4">📤 上传知识库</h2>
        <input id="ragTagInput" type="text" placeholder="请输入知识库名称（ragTag）"
               class="w-full px-4 py-2 border rounded-lg shadow-sm mb-3 focus:ring-2 focus:ring-blue-400"/>
        <input id="knowledgeFiles" type="file" multiple
               class="w-full border px-4 py-2 rounded-lg shadow-sm mb-3"/>
        <div class="flex justify-end space-x-3">
            <button onclick="toggleUploadModal()" class="px-4 py-2 rounded bg-gray-200 text-gray-700 hover:bg-gray-300">取消</button>
            <button id="uploadBtn" onclick="uploadKnowledge()"
                    class="px-4 py-2 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded hover:shadow-md flex items-center justify-center space-x-2">
                <span id="uploadBtnText">开始上传</span>
                <svg id="uploadSpinner" class="w-4 h-4 hidden animate-spin" fill="none" stroke="currentColor"
                     viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M12 4v1m6.364 1.636l-.707.707M20 12h-1M4 12H3m2.343-5.657l-.707-.707M12 20v-1m-6.364-1.636l.707-.707M4 12H3"></path>
                </svg>
            </button>
        </div>
        <div id="uploadResult" class="text-sm mt-3 text-gray-600"></div>
    </div>
</div>
<!-- 全局加载遮罩 -->
<div id="globalLoading" class="fixed inset-0 bg-black/40 z-[999] hidden items-center justify-center flex">
    <div class="flex flex-col items-center space-y-4">
        <svg class="w-10 h-10 text-white animate-spin" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10"
                    stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor"
                  d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
        </svg>
        <span class="text-white text-sm">正在上传，请稍候...</span>
    </div>
</div>


<!--知识库列表-->
<script>

    function toggleRagListModal() {
        const modal = document.getElementById('ragListModal');
        modal.classList.toggle('hidden');
        if (!modal.classList.contains('hidden')) {
            fetchRagTagList();
        } else {
            // 隐藏时清空内容
            const container = document.getElementById('ragListContainer');
            container.innerHTML = '';
            document.getElementById('ragListError').classList.add('hidden');
            document.getElementById('ragListLoading').classList.add('hidden');
        }
    }

    async function fetchRagTagList() {
        const container = document.getElementById('ragListContainer');
        const loading = document.getElementById('ragListLoading');
        const errorEl = document.getElementById('ragListError');

        container.innerHTML = '';
        errorEl.classList.add('hidden');
        loading.classList.remove('hidden');

        try {
            const response = await fetch(`${apiBaseUrl}/api/v1/rag/queryRagTagList`, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            });
            const result = await response.json();

            loading.classList.add('hidden');

            if (result.code === '0000' && Array.isArray(result.data)) {
                if (result.data.length === 0) {
                    container.innerHTML = '<li>无知识库数据</li>';
                } else {
                    container.innerHTML = result.data.map(tag => `<li>${tag}</li>`).join('');
                }
            } else {
                errorEl.textContent = '获取知识库列表失败：' + (result.info || '未知错误');
                errorEl.classList.remove('hidden');
            }
        } catch (error) {
            loading.classList.add('hidden');
            errorEl.textContent = '请求异常，请检查网络或服务器';
            errorEl.classList.remove('hidden');
            console.error('fetchRagTagList error:', error);
        }
    }

</script>

<script>
    function showGlobalLoading() {
        document.getElementById('globalLoading').classList.remove('hidden');
    }
    function hideGlobalLoading() {
        document.getElementById('globalLoading').classList.add('hidden');
    }


    const apiBaseUrl = 'http://localhost:8090';

    function toggleUploadModal() {
        const modal = document.getElementById('uploadModal');
        modal.classList.toggle('hidden');
        // 重置状态
        document.getElementById('ragTagInput').value = '';
        document.getElementById('knowledgeFiles').value = '';
        document.getElementById('uploadResult').textContent = '';
        setUploading(false);
    }
    function setUploading(isUploading) {
        const uploadBtn = document.getElementById('uploadBtn');
        const uploadText = document.getElementById('uploadBtnText');
        const spinner = document.getElementById('uploadSpinner');

        uploadBtn.disabled = isUploading;
        if (isUploading) {
            uploadText.textContent = '上传中...';
            spinner.classList.remove('hidden');
        } else {
            uploadText.textContent = '开始上传';
            spinner.classList.add('hidden');
        }
    }

    /**
     * 上传知识库
     * @returns {Promise<void>}
     */
    async function uploadKnowledge() {
        const ragTag = document.getElementById('ragTagInput').value.trim();
        const files = document.getElementById('knowledgeFiles').files;
        const resultEl = document.getElementById('uploadResult');

        if (!ragTag || files.length === 0) {
            resultEl.textContent = '⚠️ 请填写知识库名称并选择文件。';
            resultEl.className = 'text-red-500 mt-3';
            return;
        }

        const formData = new FormData();
        formData.append('ragTag', ragTag);
        for (let file of files) {
            formData.append('file', file);
        }

        try {
            showGlobalLoading();

            const response = await fetch(`${apiBaseUrl}/api/v1/rag/file/upload`, {
                method: 'POST',
                body: formData
            });

            const result = await response.json();

            if (result.code === '0000') {
                resultEl.textContent = `✅ ${result.info || '上传成功！'}`;
                resultEl.className = 'text-green-600 mt-3';

                setTimeout(() => {
                    toggleUploadModal();
                }, 3000);
            } else {
                resultEl.textContent = `❌ 上传失败：${result.info || '未知错误'}`;
                resultEl.className = 'text-red-500 mt-3';
            }

        } catch (error) {
            console.error('上传失败:', error);
            resultEl.textContent = '❌ 上传出错，请检查网络或服务器。';
            resultEl.className = 'text-red-500 mt-3';

        } finally {
            hideGlobalLoading();
        }
    }

</script>

<!-- 聊天逻辑加载 -->
<script>
    class AIChat {
        constructor() {
            this.messagesContainer = document.getElementById('messagesContainer');
            this.messageInput = document.getElementById('messageInput');
            this.sendButton = document.getElementById('sendButton');
            this.modelSelect = document.getElementById('modelSelect');
            this.statusIndicator = document.getElementById('statusIndicator');
            this.statusText = document.getElementById('statusText');
            this.charCount = document.getElementById('charCount');
            this.sendIcon = document.getElementById('sendIcon');
            this.sendText = document.getElementById('sendText');

            this.isStreaming = false;
            this.currentEventSource = null;

            this.initEventListeners();
            this.autoResizeTextarea();
        }

        initEventListeners() {
            this.sendButton.addEventListener('click', () => this.sendMessage());

            this.messageInput.addEventListener('keydown', (e) => {
                if (e.ctrlKey && e.key === 'Enter') {
                    e.preventDefault();
                    this.sendMessage();
                }
            });

            this.messageInput.addEventListener('input', () => {
                const length = this.messageInput.value.length;
                this.charCount.textContent = `${length}/1000`;
                this.autoResizeTextarea();
            });
        }

        autoResizeTextarea() {
            this.messageInput.style.height = 'auto';
            this.messageInput.style.height = Math.min(this.messageInput.scrollHeight, 500) + 'px';
        }

        async sendMessage() {
            const message = this.messageInput.value.trim();
            if (!message || this.isStreaming) return;

            const qaMode = document.getElementById('qaModeSelect').value;
            const selectedRagTag = document.getElementById('ragTagSelector')?.value || '';

            if (qaMode === 'rag' && !selectedRagTag) {
                alert('请选择一个知识库进行问答');
                return;
            }


            const model = this.modelSelect.value;

            this.addMessage(message, 'user');
            this.messageInput.value = '';
            this.charCount.textContent = '0/1000';
            this.autoResizeTextarea();

            await this.streamResponse(model, message);
        }

        addMessage(content, type) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `flex ${type === 'user' ? 'justify-end' : 'justify-start'} animate-fade-in`;

            const messageContent = document.createElement('div');

            if (type === 'assistant') {
                messageContent.className = 'max-w-4xl bg-white/80 backdrop-blur-sm border border-gray-200/50 rounded-2xl p-6 shadow-lg hover:shadow-xl transition-all duration-200 mr-12';
                messageContent.innerHTML = `
                        <div class="flex items-start space-x-4">
                            <div class="w-10 h-10 bg-gradient-to-r from-purple-500 to-blue-500 rounded-xl flex items-center justify-center text-white text-sm font-bold shadow-lg flex-shrink-0">
                                AI
                            </div>
                            <div class="flex-1 min-w-0">
                                <div class="flex items-center space-x-2 mb-2">
                                    <span class="text-sm font-semibold text-gray-700">AI助手</span>
                                    <span class="text-xs text-gray-400">${new Date().toLocaleTimeString()}</span>
                                </div>
                                <div class="text-gray-800 leading-relaxed message-content" id="content-${Date.now()}">${content}</div>
                            </div>
                        </div>
                    `;
            } else {
                messageContent.className = 'max-w-3xl bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-2xl p-6 shadow-lg ml-12';
                messageContent.innerHTML = `
                        <div class="flex items-start space-x-4 justify-end">
                            <div class="flex-1 text-right min-w-0">
                                <div class="flex items-center justify-end space-x-2 mb-2">
                                    <span class="text-xs text-blue-200">${new Date().toLocaleTimeString()}</span>
                                    <span class="text-sm font-semibold text-blue-100">您</span>
                                </div>
                                <div class="leading-relaxed message-content">${content}</div>
                            </div>
                            <div class="w-10 h-10 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center text-white text-sm font-bold flex-shrink-0">
                                U
                            </div>
                        </div>
                    `;
            }

            messageDiv.appendChild(messageContent);
            this.messagesContainer.appendChild(messageDiv);
            this.scrollToBottom();

            return messageContent;
        }

        async streamResponse(model, message) {
            this.setStreamingState(true);

            const aiMessageElement = this.addMessage('', 'assistant');
            const contentElement = aiMessageElement.querySelector('[id^="content-"]');

            contentElement.innerHTML = `
        <div class="flex items-center space-x-2">
            <div class="typing-indicator">●</div>
            <div class="typing-indicator animation-delay-200">●</div>
            <div class="typing-indicator animation-delay-400">●</div>
            <span class="ml-2 text-gray-500">正在思考...</span>
        </div>
    `;

            try {
                // 获取当前问答模式和知识库选择
                const qaMode = document.getElementById('qaModeSelect')?.value || 'normal';
                const ragTag = document.getElementById('ragTagSelector')?.value || '';

                // 构建接口路径
                const endpoint = qaMode === 'rag' ? 'generate_stream_rag' : 'generate_stream';
                let apiUrl = `${apiBaseUrl}/api/v1/ollama/${endpoint}?model=${encodeURIComponent(model)}&message=${encodeURIComponent(message)}`;

                if (qaMode === 'rag' && ragTag) {
                    apiUrl += `&ragTag=${encodeURIComponent(ragTag)}`;
                }

                this.currentEventSource = new EventSource(apiUrl);
                let fullResponse = '';

                this.currentEventSource.onmessage = (event) => {
                    try {
                        const data = JSON.parse(event.data);

                        if (data.result && data.result.output) {
                            const content = data.result.output.content || '';
                            if (content) {
                                fullResponse += content;
                                contentElement.textContent = fullResponse;
                                this.scrollToBottom();
                            }

                            if (data.result.metadata && data.result.metadata.finishReason === 'unknown') {
                                this.currentEventSource.close();
                                this.setStreamingState(false);
                            }
                        }
                    } catch (error) {
                        console.error('解析响应失败:', error);
                    }
                };

                this.currentEventSource.onerror = (error) => {
                    console.error('EventSource 错误:', error);
                    contentElement.innerHTML = `
                <div class="flex items-center space-x-2 text-red-500 bg-red-50 p-3 rounded-lg border border-red-200">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                              d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                    <span>连接失败，请检查服务器状态</span>
                </div>
            `;
                    this.currentEventSource.close();
                    this.setStreamingState(false);
                };

            } catch (error) {
                console.error('发送消息失败:', error);
                contentElement.innerHTML = `
            <div class="flex items-center space-x-2 text-red-500 bg-red-50 p-3 rounded-lg border border-red-200">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                <span>发送失败，请重试</span>
            </div>
        `;
                this.setStreamingState(false);
            }
        }


        setStreamingState(isStreaming) {
            this.isStreaming = isStreaming;
            this.sendButton.disabled = isStreaming;
            this.messageInput.disabled = isStreaming;

            if (isStreaming) {
                // 显示 loading 图标
                this.sendText.textContent = '发送中...';
                this.sendIcon.outerHTML = `
    <svg id="sendIcon" class="w-5 h-5 animate-spin text-white" xmlns="http://www.w3.org/2000/svg" fill="none"
         viewBox="0 0 24 24">
      <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
      <path class="opacity-75" fill="currentColor"
            d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
    </svg>
  `;
                this.sendIcon = document.getElementById('sendIcon'); // ✅重新绑定引用
            } else {
                // 恢复为飞机图标
                this.sendText.textContent = '发送';
                this.sendIcon.outerHTML = `
    <svg id="sendIcon" class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
            d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>
    </svg>
  `;
                this.sendIcon = document.getElementById('sendIcon'); // ✅重新绑定引用
            }


        }

        scrollToBottom() {
            setTimeout(() => {
                this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
            }, 100);
        }
    }

    document.addEventListener('DOMContentLoaded', () => {
        new AIChat();
        const btn = document.getElementById('showRagListBtn');
        btn.addEventListener('click', toggleRagListModal);
        const qaModeSelect = document.getElementById('qaModeSelect');
        const ragTagSelectorContainer = document.getElementById('ragTagSelectorContainer');
        const ragTagSelector = document.getElementById('ragTagSelector');

        qaModeSelect.addEventListener('change', async () => {
            if (qaModeSelect.value === 'rag') {
                ragTagSelectorContainer.classList.remove('hidden');

                // 加载知识库选项
                try {
                    const res = await fetch(`${apiBaseUrl}/api/v1/rag/queryRagTagList`);
                    const data = await res.json();
                    if (data.code === '0000') {
                        ragTagSelector.innerHTML = data.data.map(tag => `<option value="${tag}">${tag}</option>`).join('');
                    } else {
                        ragTagSelector.innerHTML = '<option value="">加载失败</option>';
                    }
                } catch (e) {
                    ragTagSelector.innerHTML = '<option value="">加载异常</option>';
                    console.error('加载知识库列表失败', e);
                }
            } else {
                ragTagSelectorContainer.classList.add('hidden');
            }
        });
    });

</script>


</body>
</html>
